<template>
  <div class="upd-xcjz" style="width: 700px;">
    <el-form
      :model="fm.ps" 
      :ref="fm.fname" 
      label-width="90px" 
      size="medium"
      style="margin-top: 10px">
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="过路费" 
            prop="roadFee" 
            :rules="[{ required: false, message: '请输入过路费', trigger: 'blur' },
              this.$rules.isFloat('过路费必须大于0')
            ]">
            <el-input 
              placeholder="过路费" 
              maxlength="6"
              v-model="fm.ps.roadFee"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item 
            label="打单费" 
            prop="singleFee" 
            :rules="[{ required: false, message: '请输入打单费', trigger: 'blur' },
              this.$rules.isFloat('打单费必须大于0')
            ]">
            <el-input 
              placeholder="打单费" 
              maxlength="6"
              v-model="fm.ps.singleFee"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item 
            label="生活费" 
            prop="livingFee" 
            :rules="[
              { required: false, message: '请输入生活费', trigger: 'blur' },
              this.$rules.isFloat('生活费必须大于0')
            ]">
            <el-input 
              placeholder="生活费" 
              maxlength="6"
              v-model="fm.ps.livingFee"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item 
            label="住宿费" 
            prop="stayFee" 
            :rules="[
              { required: false, message: '请输入住宿费', trigger: 'blur' },
              this.$rules.isFloat('住宿费必须大于0')
            ]">
            <el-input 
              placeholder="住宿费" 
              maxlength="6"
              v-model="fm.ps.stayFee"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item 
            label="买水费" 
            prop="waterFee" 
            :rules="[
              { required: false, message: '请输入买水费', trigger: 'blur' },
              this.$rules.isFloat('买水费必须大于0')
            ]">
            <el-input 
              placeholder="买水费" 
              maxlength="6"
              v-model="fm.ps.waterFee"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item 
            label="洗车费" 
            prop="washingFee" 
            :rules="[
              { required: false, message: '请输入洗车费', trigger: 'blur' },
              this.$rules.isFloat('洗车费必须大于0')
            ]">
            <el-input 
              placeholder="洗车费" 
              maxlength="6"
              v-model="fm.ps.washingFee"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item 
            label="其他费" 
            prop="otherFee" 
            :rules="[
              { required: false, message: '请输入其他费', trigger: 'blur' },
              this.$rules.isFloat('其他费必须大于0')
            ]">
            <el-input 
              placeholder="其他费" 
              maxlength="6"
              v-model="fm.ps.otherFee"
            />
          </el-form-item>
        </el-col>
      
        <el-col :span="12">
          <!-- <el-form-item 
            label="凭证"
            prop="routeVoucherUrl"
            :rules="[{ validator: fm.valRouteVoucherUrl, trigger: 'change' }]"
            required>
            <UploadImg
              style="margin-right: 10px;display: inline-block;"
              v-for="(it,index) in fm.ps.routeVoucherUrl"
              :key="index"
              imgName="routeVoucherUrl"
              @getImgUrl="(data) => setImgUrl(data, index)"
              url="/company/upload"
              :ps="{userName: uname}"
              :src="fileBaseUrl+it.url"
            />
          </el-form-item> -->
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item 
            label="凭证"
            prop="routeVoucherUrl"
            :rules="[{ validator: fm.valRouteVoucherUrl, trigger: 'change' }]"
            required>
            <UploadImg
              style="margin-right: 10px;display: inline-block;"
              v-for="(it,index) in fm.ps.routeVoucherUrl"
              :key="index"
              imgName="routeVoucherUrl"
              @getImgUrl="(data) => setImgUrl(data, index)"
              url="/company/upload"
              :ps="{userName: uname}"
              :src="fileBaseUrl+it.url"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-for="(it, index) in fm.ps.parkingDetails" :key="index">
        <el-col :span="12">
          <el-form-item
            label="停车费"
            :prop="`parkingDetails.${index}.parkingFee`"
            :rules="[
              { required: false, message: '请输入停车费', trigger: 'blur' },
              { pattern: /^(([1-9]\d*)|0)(\.\d{1,2})?$/, message: '停车费金额格式错误', trigger: 'blur' },
            ]">
            <el-input 
              placeholder="停车费" 
              maxlength="6"
              v-model="it.parkingFee"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item 
            label="停车位置"
            :prop="`parkingDetails.${index}.position.name`">
            <MapPointInp 
              :name="'position'" 
              :pindex="index" 
              :placeholder="'停车位置'" 
              :defPoint="it.position"
              @handleSel="setPoint"
              style="width: 165px;"
            />

            <el-button 
              style="margin-left: 10px" 
              type="primary" 
              icon="el-icon-plus" 
              circle 
              @click="addPosition"
            />

            <el-button 
              v-if="index !== 0" 
              style="margin-left: 10px" 
              type="danger" 
              icon="el-icon-minus" 
              circle
              @click="delPosition(index)"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <div class="fm-btn-row">
      <el-button 
        :loading="fm.sb.load" 
        type="primary" 
        icon="el-icon-check"
        @click="onSubmit">
        {{fm.sb.text}}
      </el-button>
    </div>
  </div>
</template>

<script>
import {mapGetters} from "vuex";

import UploadImg from '@/components/UploadImg';
import MapPointInp from '@/components/MapPointInp';

import * as orderSer from "@/api/services/order.service";

export default {
  name: "UpdXcjz",
  components: {UploadImg, MapPointInp},
  props: { myData: Object },
  computed: { ...mapGetters(["uname"]) },
  data() {
    // 验证-行程报账凭证图片
    let valRouteVoucherUrl = (rule, value, callback) => {
      if(!value[0].url) callback(new Error('请选择图片'));
      callback();
    };
    return {
      // 文件地址前缀
      fileBaseUrl: this.C.fileBaseUrl,
      fm: {
        fname: 'updXcjzFm',
        sb: {load: false, text: '提交申请'},
        valRouteVoucherUrl,
        ps: {
          // 记账对象id
          uid: '',
          // 生活费
          livingFee: '',
          // 订单编号 
          orderNum: '', 
          // 其他费用
          otherFee: '', 
          // 过路费
          roadFee: '',  
          // 打单费
          singleFee: '',
          // 住宿费 
          stayFee: '', 
          // 洗车费
          washingFee: '',
          // 买水费 
          waterFee: '', 
          // 记账凭证图片
          routeVoucherUrl: [ {url: ''} ],
          // 停车详情
          parkingDetails: [{
            parkingFee: '', 
            position: {
              address: '',
              name: '',
              lnglat: '',
            },
          }], 
        }
      },
      
    }
  },
  created() {
    this.init();
  },
  methods: {
    init(){
      const that = this, {obj} = that.myData, ps = that.fm.ps;

      let o = obj?.orderTrade
      if(o){
        // 员工记账对象id
        ps.uid = obj.id;
        // 订单编号 
        ps.orderNum = o.orderNum; 
        // 生活费
        ps.livingFee = o.livingFee;
        // 其他费用
        ps.otherFee = o.otherFee; 
        // 过路费
        ps.roadFee = o.roadFee; 
        // 打单费
        ps.singleFee = o.singleFee;
        // 住宿费 
        ps.stayFee = o.stayFee; 
        // 洗车费
        ps.washingFee = o.washingFee;
        // 买水费 
        ps.waterFee = o.waterFee;
        // 记账凭证图片
        o.routeVoucherUrl?.split(',').forEach(it => {
          ps.routeVoucherUrl.unshift({url: it});
        });
        // 停车详情
        let parkingDetailsArr = [];
        o.routeTradeId?.forEach(it => {
          parkingDetailsArr.push({
            parkingFee: it.parkingFee, 
            position: {
              address: it.position,
              name: it.position,
              lnglat: it.lngLat,
            },
          }); 
        });
        if(parkingDetailsArr.length > 0) ps.parkingDetails = parkingDetailsArr;

      }
    },

    // 设置图片
    setImgUrl(data, index) {
      const that = this, U = that.U, ps = that.fm.ps;

      // 如果是删除
      if (!data.url) {
        if(ps.routeVoucherUrl.length > 1) ps.routeVoucherUrl.splice(index, 1);
      }else{
        ps.routeVoucherUrl[index].url = data.url;
        if (ps.routeVoucherUrl.length < 8) {
          ps.routeVoucherUrl.push({url: ''});
        }

        if(ps.routeVoucherUrl.length > 0){
          U.clearFmVali(that, that.fm.fname, `routeVoucherUrl`);
        }
      }
    },

    // 设置地点
    setPoint(e){
      let that = this, fm = that.fm, points = fm.ps.parkingDetails;
      
      if(e.p){
        let point = points[e.pindex];

        point[e.name] = {
          address: e.p.address, 
          name: e.p.name, 
          lnglat: e.p.lnglat, 
        };
      }else{
        let point = points[e.pindex];
        
        point[e.name] = {
          address: '', 
          name: '', 
          lnglat: '', 
        };
      }
    },
    
    // 添加-停车位置项
    addPosition() {
      this.fm.ps.parkingDetails.push({
        parkingFee: '', 
        position: {
          address: '',
          name: '',
          lnglat: '',
        },
      });
    },
    // 删除-停车位置项
    delPosition(index) {
      this.fm.ps.parkingDetails.splice(index, 1);
    },

    // 验证-各种费用至少填写一个 
    valOnlyOne(){
      let that = this, fg = false, ps = that.U.scopy(that.fm.ps);

      if(!fg){
        if(ps.livingFee && parseFloat(ps.livingFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.otherFee && parseFloat(ps.otherFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.roadFee && parseFloat(ps.roadFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.singleFee && parseFloat(ps.singleFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.stayFee && parseFloat(ps.stayFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.washingFee && parseFloat(ps.washingFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.waterFee && parseFloat(ps.waterFee) > 0){
          fg = true;
        }
      }

      if(!fg){
        if(ps.parkingDetails && ps.parkingDetails[0].parkingFee && parseFloat(ps.parkingDetails[0].parkingFee) > 0){
          fg = true;
        }
      }

      return fg;
    },

    // 提交表单
    onSubmit() {
      let that = this, U = that.U, fm = that.fm, sb = fm.sb, ps = U.scopy(fm.ps), {obj} = that.myData;

      that.$refs[fm.fname].validate((valid) => {
        if (!valid) { return false; } else {
          if(!that.valOnlyOne()){
            U.qerror('请至少填写一种费用');
          }else if(!obj.orderTrade){
            U.qerror('修改报账记录不存在，请关闭弹框重新选择');
          }else{
            let fg = true;

            if(fg){
              // 保存-订单编号
              ps.orderNum = obj.orderTrade.orderNum;

              // 处理-图片地址
              let routeVoucherUrl = [];
              ps.routeVoucherUrl.forEach(it => {
                if(it.url) routeVoucherUrl.push(it.url);
              });
              ps.routeVoucherUrl = routeVoucherUrl.join(',');
            }
            
            if(fg){
              // 处理-停车费数据
              let parkingDetails = [];

              for(let i = 0; i < ps.parkingDetails.length; i++){
                let it = ps.parkingDetails[i];
                if(it.parkingFee && !it.position.lnglat){
                  fg = U.qerror(`第${i+1}个停车位置不能为空`);
                  break;
                }else if((!it.parkingFee || it.parkingFee == 0) && it.position.lnglat){
                  fg = U.qerror(`第${i+1}个停车费不能为空或0`);
                  break;
                }else if((it.parkingFee && it.parkingFee != 0) && it.position.lnglat){
                  parkingDetails.push({
                    parkingFee: it.parkingFee,
                    position: it.position.name,
                    lonAndLat: it.position.lnglat,
                  });
                }
              }
              ps.parkingDetails = parkingDetails;
            }
            
            if(fg){
              sb.load = true

              // 更新
              orderSer.updCompanyXcjz(ps).then(res => {
                sb.load = false;

                if (res.code !== 1) {
                  U.qerror(res.msg);
                }else{
                  U.qsuccess(res.msg);

                  that.$emit("closeMd");
                  that.$emit("reloadDg");
                }
              });

              setTimeout(() => { sb.load = false; }, 10000);
            }
          }
        }
      });
    },


  }
}
</script>